<template>
    <div class="app-container">
        <el-row :gutter="10">
            <el-col :span="5" v-show="!pack">
                <el-form>
<!--                    <el-form-item>
                        <el-tooltip class="item" effect="dark" content="用于更新排站信息后的刷新,谨慎使用" placement="top" style="float: left">
                            <el-button type="primary" icon="el-icon-refresh" size="small" plain
                                       @click="instruct('update_session_info')">刷新房间配置
                            </el-button>
                        </el-tooltip>
                    </el-form-item>-->
                    <el-form-item label="选择考试">
                        <el-select v-model="examId" placeholder="请选择考试" @change="getExamTodayDataById"
                                   style="width: 80%" clearable class="input-200">
                            <el-option v-for="item in exam_list" :key="item.id" :label="item.name" :value="item.id"
                                       :disabled="item.allotStatus==1">
                                {{ item.name }}({{ item.allotStatus == 1 ? '未' : '已' }}排站)
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
                <el-empty v-if="isEmpty(exam_data)" description="未查询到场地"/>
                <el-tabs v-else v-model="timeId" tab-position="left" style="margin-top: 10px">
                    <el-tab-pane v-for="(placeMap,timeIdd) in exam_data" :label="time_map[timeIdd].name"
                                 :name="timeIdd">
                        <div v-for="(placeLists,placeIdd) in placeMap" class="place_list__box">
                            <div class="place_list__box">
                                <el-descriptions :column="2" :colon="false" size="mini" direction="vertical">
                                    <template slot="title">
                                        <el-tag type="success">
                                            {{ place_map[placeIdd].placeName }}
                                        </el-tag>
                                    </template>
                                    <template slot="extra">
                                        <el-link type="danger" disabled>
                                            {{ placeLists.length }}
                                        </el-link>
                                    </template>
                                    <el-descriptions-item v-for="(userList,index) in placeLists">
                                        <el-badge v-if="connect_data[`${examId}-${timeId}-${placeIdd}-${index}`]['show']" value="展示端连接" class="item">
                                            <el-button type="primary" plain @click="chooseExam(placeIdd,index)" size="small">
                                                {{ place_map[placeIdd].placeName }}-{{ index + 1 }}
                                            </el-button>
                                        </el-badge>
                                        <el-badge v-else value="未连接" type="info" class="item">
                                            <el-button type="primary" plain @click="chooseExam(placeIdd,index)" size="small"
                                                       :disabled="connect_data[`${examId}-${timeId}-${placeIdd}-${index}`]['ctrl'][examinerType]">
                                                {{ place_map[placeIdd].placeName }}-{{ index + 1 }}
                                            </el-button>
                                        </el-badge>
                                    </el-descriptions-item>
                                </el-descriptions>
                            </div>
                        </div>
                    </el-tab-pane>
                </el-tabs>
            </el-col>
            <el-col :span="0.3" class="pack">
                <el-tooltip class="item" effect="dark" :content="pack ? '展开' : '收起'" placement="right">
                    <el-link type="info" :underline="false" @click="pack = !pack"><i :class="pack ? 'el-icon-d-arrow-right' : 'el-icon-d-arrow-left'"></i></el-link>
                </el-tooltip>
            </el-col>
            <el-col :span="pack ? 23 : 18">
                <IN_VIEW ref="in_view" @instruct="instruct"/>
            </el-col>
        </el-row>
    </div>
</template>

<script>
import {get_exam_today_data_by_id,} from "@/api/score/score_ex_exam";
import IN_VIEW from './in_view.vue';
import {copyObj, fillObj, isEmpty, isEmptyStr, isNotEmpty, parseObj, toJsonStr} from "@/utils/zzDouUtils/objUtil";
import {getToken} from "@/utils/auth";
//考试信息展示屏

export default {
    name: "scoreExamPlaceCtrl",
    components: {IN_VIEW},
    data() {
        return {
            pack: false,//是否折叠
            exam_list: [],
            exam_data: null,
            connect_data: null,
            examinerType: null,
            time_map: {},
            place_map: {},
            examId: null,
            timeId: null,
            placeId: null,
            index: null,
            in_exam: null,
            domain: process.env.VUE_APP_BASE_API,
            socket: null,
            notify_duration: 1000,
        };
    },
    created() {
        this.initConnect();
    },
    watch: {},
    methods: {
        isEmpty,
        /** 根据id获取考试今日的详情 */
        getExamTodayDataById(examId) {
            if (examId == null || isEmptyStr(examId)) {
                this.exam_data = null;
                this.time_map = {};
                this.place_map = {};
                this.timeId = null;
                return;
            }
            this.examId = examId;
            const request = {
                order: 'get_exam_today_data_by_id',
                examId: examId
            }
            this.sendWebSocketMsg(toJsonStr(request));
        },
        /** 选择场地 */
        chooseExam(placeId, index) {
            if (placeId == this.placeId && index == this.index) {
                return;
            }
            this.placeId = placeId;
            this.index = index;
            this.$refs.in_view.placeId = placeId;
            this.instruct('choose_exam');
            //赋值给小窗口
            let obj;
            this.exam_list.forEach(ex=>{
                if (ex.id === this.examId){
                    obj = copyObj(ex);
                    return;
                }
            })
            obj.timeId = this.timeId;
            obj.index = index;
            obj.place = this.place_map[placeId];
            this.$refs.in_view.exam = obj;
        },
        //下发命令
        instruct(order,obj) {
            let request = {
                order: order,
                examId: this.examId,
                timeId: this.timeId,
                placeId: this.placeId,
                index: this.index,
            }
            if (isNotEmpty(obj)){
                request = fillObj(request,obj);
            }
            this.sendWebSocketMsg(toJsonStr(request));
        },
        initConnect() {
            this.socket = new WebSocket(`ws://${isEmptyStr(this.domain) ? window.location.host : this.domain}/score-exam-place?role=ctrl&&token=${getToken()}`)
            // 监听 WebSocket 事件
            this.socket.addEventListener('open', event => {
                this.$notify.success({title: '成功', message: '连接成功', duration: this.notify_duration});
            })
            // 接收到实时数据
            this.socket.addEventListener('message', event => {
                this.listenMessage(event.data)
            })
            this.socket.addEventListener('close', event => {
                this.$notify.error({title: '错误', message: '与后端程序断开连接', duration: this.notify_duration});
            })
            this.socket.addEventListener('error', event => {
                this.$notify.error({title: '错误', message: '与后端程序通讯发生错误', duration: this.notify_duration});
            })
        },
        listenMessage(response) {
            let result = parseObj(response);
            if (result.code == '500') {
                this.$notify.error({title: '错误', message: result.msg, duration: this.notify_duration});
            }
            switch (result.order) {
                case 'update_waiting_users': {
                    if (result.request.examId == this.examId && result.request.timeId == this.timeId) {
                        const data = result.data;
                        let userList = data['userList'][this.placeId + '-' + this.index]['stus'];
                        this.$refs.in_view.userList = userList;
                        this.$refs.in_view.peopleMap = data.peopleMap;
                        let examOvers = data.examOvers[this.placeId + '-' + this.index];
                        this.$refs.in_view.examOvers = isEmpty(examOvers) ? {} : examOvers[this.examinerType];
                        this.$refs.in_view.sheetMap = data.sheetMap;
                    }
                }break;
                case 'today_exam_list': {
                    this.exam_list = result.data;
                    this.connect_data = result.connectData;
                }break;
                case 'update_connect_data': {
                    this.connect_data = result.data;
                }break;
                case 'update_session_info': {
                    this.$notify.success({title: '成功', message: result.msg, duration: this.notify_duration});
                }break;
                case 'call_code': {
                    this.$notify.success({title: '成功', message: result.msg, duration: this.notify_duration});
                }break;
                case 'get_exam_today_data_by_id': {
                    this.exam_data = result.data.data;
                    this.time_map = result.data.timeMap;
                    this.place_map = result.data.placeMap;
                    this.timeId = Object.keys(this.time_map)[0];
                }break;
                case 'choose_exam': {
                    this.$refs.in_view.examinerType = result.examinerType;
                    this.examinerType = result.examinerType;
                    this.$refs.in_view.skill = result.skill;
                    this.$refs.in_view.sheetStr = result.sheet;
                    this.$refs.in_view.score = null;
                    this.$refs.in_view.nameShow = result.data.nameShow;
                    let examOvers = result.data.examOvers[this.placeId + '-' + this.index];
                    this.$refs.in_view.examOvers = isEmpty(examOvers) ? {} : examOvers[this.examinerType];
                }break;
                case 'select_sheet': {
                    this.$refs.in_view.sheet = result.data;
                    this.$refs.in_view.sessionId = result.sessionId;
                }break;
                case 'save_mark': {
                    this.$notify.success({title: '打分', message: result.msg, duration: this.notify_duration});
                    this.$refs.in_view.mark_open = false;
                    this.$refs.in_view.sheet = null;
                    this.$refs.in_view.sessionId = null;
                }break;
            }
        },
        sendWebSocketMsg(msg) {
            if (this.socket) this.socket.send(msg);
        },
        closeWebSocket() {
            if (this.socket != null) {
                this.socket.close();
                this.socket = null;
            }
        }
    },
    destroyed() {
        this.closeWebSocket();
    }
};
</script>
<style scoped>
.left_box {
    width: 19%;
    float: left;
}
.pack { /* 收起按钮 */
    line-height: 700px;
}
.control-class {
    width: 78%;
    height: 900px;
    float: right;
}

.place_list__box {
    width: 100%;
}
</style>
